package com.wormhole.wormholemanagement.controller;

import com.wormhole.wormholemanagement.dto.DocumentNode;
import com.wormhole.wormholemanagement.service.DocumentService;
import com.wormhole.wormholemanagement.service.NewsPhotoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/documents")
public class DocumentController {

    @Value("${baseDir}")
    private String baseDir;

    @Autowired
    private NewsPhotoService newsPhotoService;

    @Autowired
    private DocumentService documentService;

    @GetMapping("/tree")
    public DocumentNode getDocumentTree(@RequestParam(required = false) String dir) throws IOException, IOException {
        String targetDir = dir == null ? baseDir : baseDir + File.separator + dir;
        return documentService.buildDocumentTree(targetDir);
    }
    @GetMapping("/treeTest")
    public DocumentNode getDocumentTreeTest(@RequestParam(required = false) String dir) throws IOException, IOException {
        List<String> imagePaths = newsPhotoService.getAllImagePaths();

        return documentService.buildPhotoTree(imagePaths);
    }

//    TODO:超过800k就看不了
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filePath) throws IOException {
        // 构建完整文件路径（注意安全校验）
        Path file = Paths.get(baseDir).resolve(filePath).normalize();

        // 安全检查：确保文件路径在基础目录内
        if (!file.startsWith(Paths.get(baseDir).normalize())) {
            log.error("非法文件路径访问: {}", filePath);
            throw new SecurityException("非法文件路径访问");
        }

        // 检查文件是否存在
        if (!Files.exists(file) || Files.isDirectory(file)) {
            log.error("文件不存在或路径不正确: {}", filePath);
            throw new FileNotFoundException("文件不存在或路径不正确");
        }

        // 准备资源
        Resource resource = new UrlResource(file.toUri());

        // 确定内容类型
        String contentType = Files.probeContentType(file);
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        // 设置响应头
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }
}